package lv.solcraft.replication.server.rest;

import java.util.List;

import lv.solcraft.replication.server.boot.ServerConfig;
import lv.solcraft.replication.server.rest.restlets.ClientLogRestlet;

import org.restlet.Restlet;
import org.restlet.Router;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ServerRestlets implements ApplicationContextAware {

    private List<String> resources;
    private ServerConfig serverConfig;
    private ApplicationContext appContext;

    public void setResources(List<String> resources) {
        this.resources = resources;
    }

    public void configure(Router router) {
        attach(router, "/log/{site}/{event}", new ClientLogRestlet(serverConfig.getServerName()));
        for (String resourceBeanName : resources) {
            attach(router, resourceBeanName, new SpringResourceFinder(resourceBeanName, appContext));
        }
    }

    protected void attach(Router router, String pattern, Restlet restlet) {
        ErrorFilter errorFilter = new ErrorFilter();
        errorFilter.setNext(restlet);
        router.attach(pattern, errorFilter);
    }

    public void setApplicationContext(ApplicationContext appContext) throws BeansException {
        this.appContext = appContext;
    }

    public void setServerConfig(ServerConfig serverConfig) {
        this.serverConfig = serverConfig;
    }
}
